﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using UsedBookTradeSystem.DBContext;
using UsedBookTradeSystem.Models.Dtos.OutputDtos;
using UsedBookTradeSystem.Models.Enum;

namespace UsedBookTradeSystem.Controllers.BackendControllers
{
    public class OrderController : Controller
    {
        private readonly SystemDbContext _ctx;

        public OrderController(SystemDbContext ctx)
        {
            _ctx = ctx;
        }

        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> Index()
        {
            var OrderList = await _ctx.Orders.Include(x=>x.User).Include(x=>x.BookList).ToListAsync();
            ViewBag.OrderList = OrderList;
            return View();
        }

        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> Detail(int id)
        {
            var Order = await _ctx.Orders.Include(x => x.User).Include(x => x.BookList).ThenInclude(p=>p.BookInfo).FirstAsync(x=>x.Id==id);
            var Orderdetail = Order.BookList.GroupBy(x=>x.BookInfo, (k, g) => new CartInfoOutput
            {
                BookInfoId = k.Id,
                BookName = k.BookName,
                BookPicture = k.Picture,
                BookInventory = k.Inventory,
                Price = k.Price,
                BookCount = g.Count(),
                TotolPrice = g.Count() * k.Price
            }).ToList();
            ViewBag.Order = Order;
            ViewBag.Orderdetail = Orderdetail;
            return View();
        }
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> ChangeStatus(int id,OrderEnum status)
        {
            status = status switch
            {
                OrderEnum.paid=>OrderEnum.Delivery,
                OrderEnum.Delivery=>OrderEnum.Completed
            };
            var order = await _ctx.Orders.FirstAsync(x => x.Id == id);
            order.OrderStatus = status;
            _ctx.Orders.Update(order);
            await _ctx.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
    }
}
